﻿namespace CloudNinja.Metering.Data.Dapper
{
    using System;
    using System.Data;
    using System.Data.SqlClient;

    using global::Dapper;

    public class TableValueParameter : SqlMapper.IDynamicParameters
    {
        private readonly string name;

        private readonly string typeName;

        private readonly DataTable tableParameter;

        public TableValueParameter(string name, string typeName, DataTable tableParameter)
        {
            this.name = name;
            this.typeName = typeName;
            this.tableParameter = tableParameter;
        }

        public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
        {
            var sqlCommand = command as SqlCommand;
            if (sqlCommand == null)
            {
                throw new ArgumentException("Command is not a SqlCommand.", "command");
            }

            var parameter = sqlCommand.Parameters.Add(this.name, SqlDbType.Structured);
            parameter.Direction = ParameterDirection.Input;
            parameter.TypeName = this.typeName;
            parameter.Value = this.tableParameter;
        }
    }
}
